package com.laicunba.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.laicunba.constant.GloabConstant;
import com.laicunba.dao.GenericQueryDao;
import com.laicunba.pojo.MenuDO;
import com.laicunba.pojo.vo.MenuTree;
import com.laicunba.service.MenuService;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.StringUtil;

@Service
public class MenuServiceImpl extends BaseServiceImpl implements MenuService {

	@Autowired
	private GenericQueryDao queryDao;

	@Override
	public List<MenuTree> loadMenuTree(String managerUserId) {
		List<MenuTree> treeList = new ArrayList();
		List<MenuDO> menuList = GloabConstant.ROOT_USER_ID_AND_NAME.equals(managerUserId) ? list() : findByManagerUserId(managerUserId);
		if (menuList == null) {
			return treeList;
		}

		Map<String, MenuTree> map = new HashMap();
		for (MenuDO menuDO : menuList) {
			MenuTree tree = new MenuTree();
			try {
				BeanUtils.copyProperties(tree, menuDO);
				map.put(tree.getId(), tree);
				if (StringUtil.isEmpty(tree.getParentMenuId())) {
					treeList.add(tree);
				}
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		for (MenuTree tree : map.values()) {
			if (map.containsKey(tree.getParentMenuId())) {
				map.get(tree.getParentMenuId()).getChilds().add(tree);
			}
		}

		return treeList;
	}

	@Override
	public List<MenuDO> findByManagerUserId(String managerUserId) {
		return queryDao.selectList("MENU.findByManagerUserId", managerUserId);
	}

	@Override
	public List<MenuDO> list() {
		return queryDao.selectList("MENU.list", null);
	}

	@Override
	public Double getMaxSortNum() {
		return queryDao.selectOne("MENU.getMaxSortNum", null);
	}

	@Override
	public List<MenuDO> findQuickBtns(String managerUserId) {
		return queryDao.selectList("MENU.findDefaultDefQuickBtns", managerUserId);
	}

	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public void init(List<MenuDO> menuDOList) {
		Double maxSortNum = getMaxSortNum();
		maxSortNum = maxSortNum == null ? 0 : maxSortNum;
		if (menuDOList != null) {
			for (MenuDO menuDO : menuDOList) {
				if (get(MenuDO.class, menuDO.getId()) != null) {
					continue;
				}

				menuDO.setSortNum(++maxSortNum);
				AssertUtil.assertTrue(create(menuDO));
			}
		}

	}
}
